package com.jswlw.controller.admin.biz;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.jswlw.common.BaseException;
import com.jswlw.common.ResponseStatus;
import com.jswlw.controller.BaseController;
import com.jswlw.entity.base.User;
import com.jswlw.entity.biz.DevType;
import com.jswlw.entity.biz.Distributor;
import com.jswlw.service.base.UserService;
import com.jswlw.service.biz.DevTypeService;
import com.jswlw.service.biz.DistributorService;
import com.jswlw.web.manager.SessionAdminManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Objects;

@Controller
@RequestMapping("/admin/biz/distributor")
public class AdminDistributorController extends BaseController {

    @Autowired
    DistributorService service;
    @Autowired
    DevTypeService devTypeService;
    @Autowired
    UserService userService;

    @RequestMapping("/index")
    public ModelAndView index() {
        ModelAndView modelAndView=new ModelAndView();
        if (Objects.nonNull(SessionAdminManager.getCurrentUser().getDistributor())) {
            modelAndView.addObject("currLevel", SessionAdminManager.getCurrentUser().getDistributor().getLevel());
        }
        modelAndView.setViewName("biz/distributor/index");
        return modelAndView;
    }

    /**
     * 广告列表
     *
     * @param
     * @return
     */
    @RequestMapping("/list")
    @ResponseBody
    public Object list(@RequestBody Distributor distributor) {
        if (Objects.nonNull(SessionAdminManager.getCurrentUser().getDistributor())) {
            distributor.setDistributorIds(SessionAdminManager.getCurrentUser().getDistributor().getChildrenIds());
        }
        Page<Distributor> page = service.queryPage(distributor, distributor.getOffset(), distributor.getLimit());
        return pageResult(page.getResult(), page.getTotal());
    }

    /**
     * 新增广告
     *
     * @return
     */
    @RequestMapping("/add")
    public ModelAndView add() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("devTypeList", devTypeService.queryList(new DevType()));
        modelAndView.setViewName("biz/distributor/edit");
        if (Objects.nonNull(SessionAdminManager.getCurrentUser().getDistributor())) {
            modelAndView.addObject("currId", SessionAdminManager.getCurrentUser().getDistributor().getId());
        }
        return modelAndView;
    }

    /**
     * 编辑广告
     *
     * @param id
     * @return
     */
    @RequestMapping("/edit")
    public ModelAndView edit(Integer id) {
        ModelAndView modelAndView = new ModelAndView();
        Distributor distributor = service.find4Id(id);
        User user = userService.find4LoginName(String.valueOf(distributor.getId()));
        distributor.setPassword(user.getPassword());
        modelAndView.addObject("info", distributor);

        modelAndView.addObject("devTypeList", devTypeService.queryList(new DevType()));
        modelAndView.setViewName("biz/distributor/edit");
        if (Objects.nonNull(SessionAdminManager.getCurrentUser().getDistributor())) {
            modelAndView.addObject("parent", SessionAdminManager.getCurrentUser().getDistributor().getId());
            modelAndView.addObject("currId", SessionAdminManager.getCurrentUser().getDistributor().getId());
        }

        boolean isSelf = false;
        if (Objects.nonNull(SessionAdminManager.getCurrentUser().getDistributor())) {
            if (SessionAdminManager.getCurrentUser().getDistributor().getId().equals(id)) {
                isSelf = true;
            }
        }
        modelAndView.addObject("isSelf", isSelf);
        return modelAndView;
    }

    /**
     * 保存广告
     *
     * @param distributor
     * @param
     * @return
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public ModelMap save(Distributor distributor,
                         @RequestParam(value = "devTypeIds[]", required = false) List<Integer> devTypeIds) {
        try {
            distributor.setDevTypes(JSON.toJSONString(devTypeIds));

            if (distributor.getId() == null) {
                if (Objects.nonNull(SessionAdminManager.getCurrentUser().getDistributor())) {
                    Distributor curr = SessionAdminManager.getCurrentUser().getDistributor();
                    if (curr.getLevel().equals(2)) {
                        if (!distributor.getParentId().equals(curr.getId())) {
                            BaseException.sneakyThrows(ResponseStatus.BUSINESS_ERROR.getCode(), "只能添加自己下级代理商");
                        }
                    }
                }
                service.add(distributor);
            } else {
                service.update(distributor);
            }
            return this.successResult(null);
        } catch (Exception e) {
            logger.error("保存失败", e);
            return this.failResult("保存失败" + e.getMessage());
        }
    }

    /**
     * 删除广告
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ModelMap delete(Model model, Integer id) {
        try {
            service.delete(id);
            return this.successResult("删除成功");
        } catch (Exception e) {
            logger.error("保存失败", e);
            return this.failResult("删除失败" + e.getMessage());
        }
    }
}
